﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NewRetail.Application.Components.Goods.Entity;
using NewRetail.Application.Components.Platform;
using NewRetail.Application.Components.PrintTask.Entity;
using NewRetail.Application.Components.PrintTask.Model;
using NewRetail.Application.Components.Warehouse.Entity;
using NewRetail.Application.Core;
using NewRetail.Application.Core.Entity;
using NewRetail.Application.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;

namespace NewRetail.Application.Components.PrintTask
{
    #region 接口
    /// <summary>
    /// 接口
    /// </summary>
    public interface IPrintAuthorizationCodeTaskService : IApplicationService
    {
        #region 打印授权码任务相关

        /// <summary>
        /// 保存授权码打印任务
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        Task<(int, string)> SavePrintAuthorizationCodeTaskItems(PrintAuthorizationCodeTaskSaveInputDto inputDto);

        /// <summary>
        /// 更新授权码打印状态
        /// </summary>
        /// <param name="warehouseId"></param>
        /// <returns></returns>
        Task<(string, string)> UpdatePrintAuthorizationCodeTagByWarehouseId(string warehouseId);

        #endregion
    }
    #endregion

    #region 实现
    /// <summary>
    /// 实现
    /// </summary>
    public class PrintAuthorizationCodeTaskService : ApplicationService, IPrintAuthorizationCodeTaskService
    {
        #region Field
        private readonly ILogger _logger;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        protected IEntityHelper _entityHelper => this.LazyServiceProvider.LazyGetRequiredService<IEntityHelper>();
        protected INoGeneratorService _noGeneratorService => this.LazyServiceProvider.LazyGetRequiredService<INoGeneratorService>();
        private readonly IRepository<PrintAuthorizationCodeTaskEntity> _printAuthorizationCodeTaskRepository;
        private readonly IMapper _mapper;
        #endregion

        #region Constructor
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="printTaskRepository"></param>
        /// <param name="mapper"></param>
        /// <param name="unitOfWorkManager"></param>
        /// <param name="logger"></param>
        public PrintAuthorizationCodeTaskService(IRepository<PrintAuthorizationCodeTaskEntity> printAuthorizationCodeTaskRepository, IMapper mapper, IUnitOfWorkManager unitOfWorkManager,
            ILogger<PrintAuthorizationCodeTaskService> logger)
        {
            _printAuthorizationCodeTaskRepository = printAuthorizationCodeTaskRepository;
            _mapper = mapper;
            _unitOfWorkManager = unitOfWorkManager;
            _logger = logger;
        }
        #endregion

        #region method        

        #region 保存授权码打印任务
        /// <summary>
        /// 保存授权码打印任务
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<(int, string)> SavePrintAuthorizationCodeTaskItems(PrintAuthorizationCodeTaskSaveInputDto inputDto)
        {
            var result = 0;
            var errMsg = "";
            var cashierName = inputDto.cashierName;
            var warehouseId = inputDto.warehouseId;
            var authorizationCode = inputDto.authorizationCode;
            //先获取打印任务
            var db = await _printAuthorizationCodeTaskRepository.GetDbContextAsync();
            var printAuthorizationCodeTask = await db.Set<PrintAuthorizationCodeTaskEntity>().AsNoTracking().FirstOrDefaultAsync(x => x.warehouseID == warehouseId && x.cashierName == cashierName && x.printTag == 0);
            //如果不存在就新增
            if (printAuthorizationCodeTask == null)
            {
                printAuthorizationCodeTask = new PrintAuthorizationCodeTaskEntity()
                {
                    cashierName = cashierName,
                    warehouseID = warehouseId,
                    authorizationCode = authorizationCode,
                    printTag = 0,
                    printNo = "P0"
                };
                _entityHelper.InitEntity(printAuthorizationCodeTask);
                await _printAuthorizationCodeTaskRepository.InsertAsync(printAuthorizationCodeTask, autoSave: true);
                result = 1;
            }
            else
            {
                //存在则更新授权码
                printAuthorizationCodeTask.authorizationCode = authorizationCode;
                printAuthorizationCodeTask.updateTime = DateTime.Now;
                _entityHelper.SetUpdationInfo(printAuthorizationCodeTask);
                await _printAuthorizationCodeTaskRepository.UpdateAsync(printAuthorizationCodeTask);
                result = 1;
            }

            return (result, errMsg);
        }
        #endregion

        #region 更新授权码打印状态
        /// <summary>
        /// 更新授权码打印状态
        /// </summary>
        /// <param name="warehouseId"></param>
        /// <returns></returns>
        public async Task<(string, string)> UpdatePrintAuthorizationCodeTagByWarehouseId(string warehouseId)
        {
            try
            {
                var db = await _printAuthorizationCodeTaskRepository.GetDbContextAsync();
                var printAuthorizationCodeTasks = await db.Set<PrintAuthorizationCodeTaskEntity>().AsNoTracking().Where(x => x.warehouseID == warehouseId && x.printTag == 0).ToListAsync();
                if (printAuthorizationCodeTasks != null)
                {
                    foreach(var item in printAuthorizationCodeTasks)
                    {
                        item.printTag = 1;
                        item.updateTime = DateTime.Now;
                        _entityHelper.SetUpdationInfo(item);
                        await _printAuthorizationCodeTaskRepository.UpdateAsync(item, autoSave: true);
                    }
                    return ("更新成功", null);
                }
                else
                {
                    return (null, "没有要更新的记录");
                }
            }
            catch(Exception e)
            {
                return (null, e.Message);
            }
        }
        #endregion

        #endregion
    }
    #endregion
}
